﻿using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using MyApplication;
using MyData.Data.Repository;
using MyRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace MyWeb.App_Start
{
    public static class AutofacExt
    {
        private static IContainer _container;

        public static void InitAutofac()
        {
            var builder = new ContainerBuilder();
          
            //注册数据库基础操作和工作单元
            builder.RegisterGeneric(typeof(RepositoryBase<>)).As(typeof(IRepositoryBase<>));
            //  builder.RegisterType(typeof(UnitWork)).As(typeof(IUnitWork));
            //注册领域服务
            //builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(UserInfoRepository)))
            //    .Where(u => u.Namespace == "Web.Repository.Service"
            //    || u.Namespace == "Web.Repository.Interface");
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(UserInfoRepository)))
               .AsImplementedInterfaces();

            //注册app层
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(UserInfoApp)));


            //注册Repository
            //builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(UserRepository)))
            //    .AsImplementedInterfaces();

            // 注册controller，使用属性注入
            builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
            builder.RegisterModelBinderProvider();

            // builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            // 注册Api，使用属性注入
         

            // OPTIONAL: Register web abstractions like HttpContextBase.
            //builder.RegisterModule<AutofacWebTypesModule>();

            // OPTIONAL: Enable property injection in view pages.
            builder.RegisterSource(new ViewRegistrationSource());

            // 注册所有的Attribute
            builder.RegisterFilterProvider();

            // Set the dependency resolver to be Autofac.
            _container = builder.Build();

          
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
        }

        /// <summary>
        /// 从容器中获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
            //   return (T)DependencyResolver.Current.GetService(typeof(T));
        }
    }
}